package com.basic.java.threads.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试lock 锁类
 * 创建时间：2022/4/20 20:36
 *
 * @author gejin
 */
public class TestLock {
    public static void main(String[] args) {
        TestLock2 lock2 = new TestLock2();
        new Thread(lock2).start();
        new Thread(lock2).start();
        new Thread(lock2).start();
    }
}

class TestLock2 implements Runnable {
    // 默认还有10 张票
    private int ticketNum = 10;
    ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        try {
            lock.lock(); // 加锁
            while (true) {
                if (ticketNum > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticketNum--);
                } else {
                    break;
                }
            }

        } finally {
            lock.unlock(); // 解锁
        }
    }
}
